package com.lucky.xyt.core.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;

/**
 * 功能 ：时间处理类
 * 
 * @author lb
 * @version 1.0 
 */
public class DateTime {

    /** 缺省日期格式yyyy-MM-dd */
    public static final String DEFAULT_DATE_FORMAT          = "yyyy-MM-dd";
    /** 缺省时间格式HH:mm:ss */
    public static final String DEFAULT_TIME_FORMAT          = "HH:mm:ss";

    public static final String DEFAULT_TIME_MONTH_FORMAT    = "yyyy-MM";

    public static final String DEFAULT_TIME_YEAR_FORMAT     = "yyyy";
    /** 缺省月格式MONTH */
    public static final String DEFAULT_MONTH                = "MONTH";

    /** 缺省年格式YEAR */
    public static final String DEFAULT_YEAR                 = "YEAR";

    /** 缺省日格式DAY */
    public static final String DEFAULT_DAY                  = "DAY";
    /** 缺省日格式Hour */
    public static final String DEFAULT_Hour                 = "HOUR";

    /** 缺省长日期格式yyyy-MM-dd HH-mm */
    public static final String DEFAULT_DATETIME_FORMAT      = "yyyy-MM-dd HH:mm";

    /** 返回年月 yyyyMM */
    public static final String YEAR_MONTH_FORMAT            = "yyyyMM";

    /** 缺省长日期格式,精确到秒yyyy-MM-dd HH:mm:ss */
    public static final String DEFAULT_DATETIME_FORMAT_SEC  = "yyyy-MM-dd HH:mm:ss";
    /** 缺省长日期格式,精确到秒yyyyMMddHHmmss */
    public static final String DEFAULT_DATETIME_FORMAT_SEC2 = "yyyyMMddHHmmss";
    /** 缺省长日期格式,精确到毫秒yyyyMMddHHmmssS */
    public static final String DEFAULT_DATETIME_FORMAT_SEC3 = "yyyyMMddHHmmssS";
    /** 缺省长日期格式,精确到毫秒yyyyMMddHHmmssMS */
    public static final String DEFAULT_DATETIME_FORMAT_SEC4 = "yyyyMMddHHmmssMS";
    public static final String UUID_DATETIME_FORMAT         = "yyyy-MM-dd ss S";
    public static final String DISPATCHING_FORMAT           = "d日 HH:mm:ss";
    public static final String YEAR_MONTH_DATETIME_FORMAT   = "yyyy-MM";
    public static final String TJ_FORMAT                    = "M月d日";
    public static final String DEFAULT_DATE_FORMAT_CHINA    = "yyyy年M月d日";

    /**
     * 返回当前时间 Date 对象
     * 
     * @return
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 功能 ：返回时间字符串(yyyy-MM-dd HH:mm:ss) 2009-09-22 17:20:08
     * 
     * @return String
     */
    public static String getNowDateTime() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(DateTime.DEFAULT_DATETIME_FORMAT_SEC);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 功能 ：返回指定格式的当前 日期格式
     * 
     * @author zhangwei add by 2010-10-30 0:24
     * @return String
     */
    public static String getNowDateTime(String formatString) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(formatString);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(currentTime);
        return dateString;
    }
    /**
     * 格式化时间
     * @param formatString
     * @return
     */
    public static String getStringDateTime(String date,String formatString) {
        SimpleDateFormat formatter = new SimpleDateFormat(formatString);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(strToDateSample(date,DateTime.DEFAULT_DATE_FORMAT));
        return dateString;
    }

    public static String dateFormatString(Date date, String formatString) {
        if (date == null) {
            date = new Date();
        }
        SimpleDateFormat formatter = new SimpleDateFormat(formatString);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(date);
        return dateString;
    }

    /**
     * 功能 ：返回 某年某月某日 星期几 几点几分的格式 2009-09-22 17:20:28
     * 
     * @param s
     * @return String
     */
    public static String showTime(String s) {
        String timeValue = "";
        int year = getYear(s);
        int month = getMonth(s);
        int date = getDay(s);
        int hours = getHour(s);
        int minutes = getMinute(s);
        int seconds = getSecond(s);
        String week = getWeek(s);
        timeValue += year + "年";
        timeValue += ((month < 10) ? "0" : "") + month + "月";
        timeValue += ((date < 10) ? "0" : "") + date + "日  ";
        timeValue += week + "  ";
        timeValue += (hours < 12) ? "上午" : "下午";
        timeValue += ((hours <= 12) ? hours : hours - 12);
        timeValue += ((minutes < 10) ? ":0" : ":") + minutes;
        timeValue += ((seconds < 10) ? ":0" : ":") + seconds;

        return timeValue;
    }

    /**
     * 功能 ：返回日期字符串("yyyy/mm/dd hh:ss:mm")的年 2009-09-22 17:20:41
     * 
     * @param s
     * @return int
     */
    public static int getYear(String s) {
        try {
            return Integer.parseInt(s.substring(0, 4));
        } catch (Exception e) {
            return 1970;
        }
    }

    /**
     * 功能 ：返回日期字符串("yyyy/mm/dd hh:ss:mm")的月 2009-09-22 17:20:53
     * 
     * @param s
     * @return int
     */
    public static int getMonth(String s) {
        try {
            return Integer.parseInt(s.substring(5, 7));
        } catch (Exception e) {
            return 1;
        }
    }

    /**
     * 功能 ：返回日期字符串("yyyy/mm/dd hh:ss:mm")的日 2009-09-22 17:21:11
     * 
     * @param s
     * @return int
     */
    public static int getDay(String s) {
        try {
            return Integer.parseInt(s.substring(8, 10));
        } catch (Exception e) {
            return 1;
        }
    }

    /**
     * 功能 ：返回日期字符串("yyyy/mm/dd hh:ss:mm")的时 2009-09-22 17:21:20
     * 
     * @param s
     * @return int
     */
    public static int getHour(String s) {
        try {
            return Integer.parseInt(s.substring(11, 13));
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 功能 ：返回日期字符串("yyyy/mm/dd hh:ss:mm")的分 2009-09-22 17:21:30
     * 
     * @param s
     * @return int
     */
    public static int getMinute(String s) {
        try {
            return Integer.parseInt(s.substring(14, 16));
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 功能 ：返回日期字符串("yyyy/mm/dd hh:ss:mm")的秒 2009-09-22 17:21:39
     * 
     * @param s
     * @return int
     */
    public static int getSecond(String s) {
        try {
            return Integer.parseInt(s.substring(17, 19));
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 根据一个日期，返回是星期几的字符串
     * 
     * @param sdate
     * @return String
     */
    public static String getWeek(String sdate) {
        // 再转换为时间
        Date date = strToDate(sdate);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        // int hour=c.get(Calendar.DAY_OF_WEEK);
        // hour中存的就是星期几了，其范围 1~7
        // 1=星期日 7=星期六，其他类推
        return new SimpleDateFormat("EEEE").format(c.getTime());
    }

    /**
     * 功能 ：返回日期型时间 2009-09-22 17:21:50
     * 
     * @param strDate
     * @return Date
     */
    public static Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat(DateTime.DEFAULT_DATETIME_FORMAT_SEC);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }
    
    /**
     * 功能 ：根据指定格式返回日期型时间 2009-09-22 17:21:50
     * 
     * @param strDate
     * @return Date
     */
    public static Date strToDateSample(String strDate,String fomat) {
        SimpleDateFormat formatter = new SimpleDateFormat(fomat);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /**
     * 功能 ：返回时间字符串(yyyy-MM-dd HH:mm:ss) 2009-09-22 17:22:05
     * 
     * @return String
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(DateTime.DEFAULT_DATETIME_FORMAT_SEC);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 功能 ：返回时间短字符串（yyyy-MM-dd） 2010-04-16 13:37:05
     * 
     * @return String
     */
    public static String getStringShortDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(DateTime.DEFAULT_DATE_FORMAT);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 功能 ：两个时间间隔，对开始时间和结束时间大小无要求 2009-09-22 17:22:05
     * 
     * @param startTime 开始时间 格式 如："yyyy-MM-dd"
     * @param endTime 结束时间 格式 如："yyyy-MM-dd"
     * @param type 输出类型，年、月、日 如："year","month","day",对大小写不敏感
     * @return 输出固定格式，根据type确定 如："多少天"， "多少月"，"多少年"
     */
    public static int getTimeInterval(String startTime, String endTime, String type) {

        try {

            Long inv = -1l;
            java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(DateTime.DEFAULT_DATE_FORMAT);
            formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            java.text.SimpleDateFormat endformatter = new java.text.SimpleDateFormat(DateTime.DEFAULT_DATE_FORMAT);
            endformatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            Calendar rightNow = Calendar.getInstance();

            Calendar endrightNow = Calendar.getInstance();

            Date startTempdate = formatter.parse(startTime);

            Date endTempdate = endformatter.parse(endTime);

            // Long out1 = startTempdate.getTime() - endTempdate.getTime();

            rightNow.setTime(startTempdate);
            endrightNow.setTime(endTempdate);

            Long start = rightNow.getTime().getTime();
            Long end = endrightNow.getTime().getTime();
            Long result = end - start;

            String tmpField = type.toUpperCase();

            if (tmpField.equals(DEFAULT_YEAR)) {

                inv = result / (1000 * 60 * 60 * 24 * 365l);

            } else if (tmpField.equals(DEFAULT_MONTH)) {

                inv = result / (1000 * 60 * 60 * 24 * 30l);

            } else if (tmpField.equals(DEFAULT_DAY)) {

                inv = result / (1000 * 60 * 60 * 24l);
            }

            return inv.intValue();

        } catch (Exception e) {

            return 0;
        }
    }

    /**
     * 功能 ：通过季度返回月份数组
     * 
     * @param season
     * @return Integer[]
     */
    public static Integer[] getMonthBySeason(int season) {

        try {
            Integer[] month = new Integer[3];
            switch (season) {
                case 1:
                    month[0] = 1;
                    month[1] = 2;
                    month[2] = 3;
                    break;
                case 2:
                    month[0] = 4;
                    month[1] = 5;
                    month[2] = 6;
                    break;
                case 3:
                    month[0] = 7;
                    month[1] = 8;
                    month[2] = 9;
                    break;
                case 4:
                    month[0] = 10;
                    month[1] = 11;
                    month[2] = 12;
                    break;

                default:
                    break;
            }

            return month;
        } catch (Exception e) {

            return new Integer[0];
        }

    }

    /**
     * 功能 ：通过月份返回季度
     * 
     * @param month
     * @return int
     */
    public static int getSeasonByMonth(int month) {

        try {
            int season = -1;
            switch (month) {
                case 1:
                    season = 1;
                    break;
                case 2:
                    season = 1;
                    break;
                case 3:
                    season = 1;
                    break;
                case 4:
                    season = 2;
                    break;
                case 5:
                    season = 2;
                    break;
                case 6:
                    season = 2;
                    break;
                case 7:
                    season = 3;
                    break;
                case 8:
                    season = 3;
                    break;
                case 9:
                    season = 3;
                    break;
                case 10:
                    season = 4;
                    break;
                case 11:
                    season = 4;
                    break;
                case 12:
                    season = 4;
                    break;
                default:
                    season = 0;
                    break;
            }

            return season;

        } catch (Exception e) {

            return 0;
        }

    }

    /**
     * 功能 ：对于给定的时间增加天数/月数/年数后的日期,按指定格式输出
     * 
     * @param date 要改变的日期
     * @param type 日期改变的字段，如"year","month","day","hour"对大小写不敏感
     * @param interval 增加的数量(减少用负数表示),如5,-1
     * @param strFormat 输出格式,如"yyyy-MM-dd","yyyy-MM-dd hh:mm:ss",不适合单独的年月日输出
     * @return 格式化后的字符串
     */
    public static String getEndTime(String date, String type, int interval, String strFormat) {

        try {

            java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(strFormat);
            formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            Calendar rightNow = Calendar.getInstance();
            Date tempdate;
            tempdate = formatter.parse(date);

            rightNow.setTime(tempdate);

            int intField = 0;
            String tmpField = type.toUpperCase();

            intField = Calendar.DATE;
            if (tmpField.equals(DEFAULT_YEAR)) intField = Calendar.YEAR;
            if (tmpField.equals(DEFAULT_MONTH)) intField = Calendar.MONTH;
            if (tmpField.equals(DEFAULT_DAY)) intField = Calendar.DATE;
            if (tmpField.equals(DEFAULT_Hour)) intField = Calendar.HOUR;
            rightNow.add(intField, interval);
            String day = formatter.format(rightNow.getTime());

            return day;

        } catch (ParseException e) {

            return "有异常";
        }
    }

    /**
     * @return yyyyMMddHHmmss字符串
     */
    public static String getCurrentDateString() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 功能：返回某个日期几周后的某一个日期2009-11-13 13:51:45
     * 
     * @param time 日期
     * @param weeknumber 周数
     * @param weekno 一周的第几天
     * @return String
     */
    public static String getMoreWeekDay(String time, int weeknumber, int weekno) {

        String dateString = "";
        // String ltime = getLastWeekEnd(time);
        if (weeknumber == 1) {
            dateString = DateTime.getWeekSomeDay(time, weekno);
        } else {
            int sday = 0;
            // String stime = getNextWeekStart(time);

            sday = DateTime.getTimeInterval(time, DateTime.getWeekSomeDay(time, 7), DateTime.DEFAULT_DAY);
            int tday = Math.abs(sday) + (weeknumber - 1) * 7 - 1;
            dateString = DateTime.getWeekSomeDay(DateTime.getEndTime(time, DateTime.DEFAULT_DAY, tday,
                                                                     DateTime.DEFAULT_DATE_FORMAT), weekno);
        }
        return dateString;
    }

    /**
     * 功能：根据指定日期得到该天的本周的某一天2009-11-13 12:43:10
     * 
     * @param thisDay
     * @return String
     */
    public static String getWeekSomeDay(String thisDay, int wday) {
        // hour中存的就是星期几了，其范围 1~7
        // 1=星期日 7=星期六，其他类推
        String[] ss = thisDay.split("-", 3);
        Integer year = Integer.parseInt(ss[0]);
        Integer month = Integer.parseInt(ss[1]) - 1;
        Integer day = Integer.parseInt(ss[2]);
        Calendar now = Calendar.getInstance();
        now.set(year, month, day);
        int hour = now.get(Calendar.DAY_OF_WEEK);
        if (hour == 1) {
            now.set(Calendar.DATE, now.get(Calendar.DATE) - now.get(Calendar.DAY_OF_WEEK) - 7 + 1 + wday);

        } else {

            now.set(Calendar.DATE, now.get(Calendar.DATE) - now.get(Calendar.DAY_OF_WEEK) + 1 + wday);
        }
        // }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(now.getTime());
        return dateString;
    }

    /**
     * 取本周的第一天
     * 
     * @return
     */
    public static String getThisWeek() {
        Calendar now = Calendar.getInstance();
        now.set(Calendar.DATE, now.get(Calendar.DATE) - now.get(Calendar.DAY_OF_WEEK) + 1);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(now.getTime());
        return dateString;
    }

    public static String getThisWeekFirst() // add syh
    {
        Calendar now = Calendar.getInstance();
        now.set(Calendar.DATE, now.get(Calendar.DATE) - now.get(Calendar.DAY_OF_WEEK) + 1);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(now.getTime());
        return dateString;
    }

    public static String getThisWeekSecond() // add syh
    {
        Calendar now = Calendar.getInstance();
        now.set(Calendar.DATE, now.get(Calendar.DATE) - now.get(Calendar.DAY_OF_WEEK) + 1 + 1);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(now.getTime());
        return dateString;
    }

    public static String getThisWeekEnd() // add syh
    {
        Calendar now = Calendar.getInstance();
        now.set(Calendar.DATE, now.get(Calendar.DATE) - now.get(Calendar.DAY_OF_WEEK) + 1 + 6);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(now.getTime());
        return dateString;
    }

    /**
     * 计算两个日期间相差多少周.日期格式yyyy-MM-dd
     * 
     * @param startTime
     * @param endTime
     * @author syh
     * @return
     */
    public static int computeWeeks(String startTime, String endTime) {
        // 注意这里的月份都没有减一,按道理来讲中国的月份相对与Calendar.MONTH少一个,因为Calendar.MONTH是从0开始的,但是这里如果减1了后,结果全部错位,而不减1后全又是全部正确的
        Calendar beginCalendar = null;
        beginCalendar = new GregorianCalendar();

        int yy = Integer.parseInt(startTime.split("-")[0]);
        int mm = Integer.parseInt(startTime.split("-")[1]);
        int dd = Integer.parseInt(startTime.split("-")[2]);
        beginCalendar.set(yy, mm, dd);

        Calendar endCalendar = null;
        endCalendar = new GregorianCalendar();
        int yy1 = Integer.parseInt(endTime.split("-")[0]);
        int mm1 = Integer.parseInt(endTime.split("-")[1]);
        int dd1 = Integer.parseInt(endTime.split("-")[2]);
        endCalendar.set(yy1, mm1, dd1);

        int weeks = 0;
        while (beginCalendar.before(endCalendar)) {
            // 如果开始日期和结束日期在同年、同月且当前月的同一周时结束循环
            if (beginCalendar.get(Calendar.YEAR) == endCalendar.get(Calendar.YEAR)
                && beginCalendar.get(Calendar.MONTH) == endCalendar.get(Calendar.MONTH)
                && beginCalendar.get(Calendar.DAY_OF_WEEK_IN_MONTH) == endCalendar.get(Calendar.DAY_OF_WEEK_IN_MONTH)) {
                break;
            } else {
                beginCalendar.add(Calendar.DAY_OF_YEAR, 7);
                weeks += 1;
            }
        }
        return weeks;
    }

    /**
     * 这里不是指的相隔七天，比如2008-08-01 到 2008-08-21 则返回3 因为相隔3周
     * 
     * @param startTime
     * @param endTime
     * @return
     */
    public static int computeWeeksChina(String startTime, String endTime) {
        // 注意这里的月份都没有减一,按道理来讲中国的月份相对与Calendar.MONTH少一个,因为Calendar.MONTH是从0开始的,但是这里如果减1了后,结果全部错位,而不减1后全又是全部正确的
        Calendar beginCalendar = null;
        beginCalendar = new GregorianCalendar();

        int yy = Integer.parseInt(startTime.split("-")[0]);
        int mm = Integer.parseInt(startTime.split("-")[1]) - 1;
        int dd = Integer.parseInt(startTime.split("-")[2]);
        beginCalendar.set(yy, mm, dd);
        Calendar endCalendar = null;
        endCalendar = new GregorianCalendar();
        int yy1 = Integer.parseInt(endTime.split("-")[0]);
        int mm1 = Integer.parseInt(endTime.split("-")[1]) - 1;
        int dd1 = Integer.parseInt(endTime.split("-")[2]);
        endCalendar.set(yy1, mm1, dd1);
        int weeks = 0;
        while (beginCalendar.before(endCalendar)) {
            // 如果开始日期和结束日期在同年、同月且当前月的同一周时结束循环
            if (beginCalendar.get(Calendar.YEAR) == endCalendar.get(Calendar.YEAR)
                && beginCalendar.get(Calendar.MONTH) == endCalendar.get(Calendar.MONTH)
                && beginCalendar.get(Calendar.WEEK_OF_MONTH) == endCalendar.get(Calendar.WEEK_OF_MONTH)) {
                break;
            } else {
                beginCalendar.add(Calendar.DAY_OF_YEAR, 7);
                weeks += 1;
            }
        }
        return weeks;
    }

    /**
     * 功能：返回中国规范的相差周数 只要相隔周日就算一周（从周六到下周一也是相隔2周）2009-11-10 12:30:25
     * 
     * @param startTime开始时间
     * @param endTime结束时间
     * @return int
     */
    public static int computeWeeksChinaMode(String startTime, String endTime) {
        // 注意这里的月份都没有减一,按道理来讲中国的月份相对与Calendar.MONTH少一个,因为Calendar.MONTH是从0开始的,但是这里如果减1了后,结果全部错位,而不减1后全又是全部正确的
        Calendar beginCalendar = null;
        beginCalendar = new GregorianCalendar();
        String stime = getNextWeekStart(startTime);
        String ltime = getLastWeekEnd(endTime);
        int yy = Integer.parseInt(stime.split("-")[0]);
        int mm = Integer.parseInt(stime.split("-")[1]) - 1;
        int dd = Integer.parseInt(stime.split("-")[2]);
        beginCalendar.set(yy, mm, dd);
        Calendar endCalendar = null;
        endCalendar = new GregorianCalendar();
        int yy1 = Integer.parseInt(ltime.split("-")[0]);
        int mm1 = Integer.parseInt(ltime.split("-")[1]) - 1;
        int dd1 = Integer.parseInt(ltime.split("-")[2]);
        endCalendar.set(yy1, mm1, dd1);
        int weeks = 0;
        while (beginCalendar.before(endCalendar)) {
            // 如果开始日期和结束日期在同年、同月且当前月的同一周时结束循环
            if (beginCalendar.get(Calendar.YEAR) == endCalendar.get(Calendar.YEAR)
                && beginCalendar.get(Calendar.MONTH) == endCalendar.get(Calendar.MONTH)
                && beginCalendar.get(Calendar.WEEK_OF_MONTH) == endCalendar.get(Calendar.WEEK_OF_MONTH)) {
                break;
            } else {
                beginCalendar.add(Calendar.DAY_OF_YEAR, 7);
                weeks += 1;

            }
        }
        if (weeks != 0) {
            if (!stime.equals(startTime)) {
                weeks += 1;
            }
            if (!ltime.equals(endTime)) {

                weeks += 1;
            }
        } else {
            weeks += 1;
        }
        return weeks;
    }

    /**
     * 得到指定日期下一周的开始时间 注意此方法仅针对中国习惯时间 即,周一是开始时间,周日是结束时间
     * 
     * @param thisTime
     * @return
     */
    public static String getNextWeekStart(String thisTime) {
        Calendar calendar = null;
        // String nowtime = getTheWeekFirst(thisTime);
        Date date = strToBirthday(thisTime);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int hour = c.get(Calendar.DAY_OF_WEEK);
        // hour中存的就是星期几了，其范围 1~7
        // 1=星期日 7=星期六，其他类推
        calendar = new GregorianCalendar();
        int yy = Integer.parseInt(thisTime.split("-")[0]);
        int mm = Integer.parseInt(thisTime.split("-")[1]) - 1;
        int dd = Integer.parseInt(thisTime.split("-")[2]);
        calendar.set(yy, mm, dd);
        if (hour == 1) {

            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);
        } else if (hour == 2) {
            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE));
        } else {

            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - calendar.get(Calendar.DAY_OF_WEEK) + 1 + 7 + 1);
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(calendar.getTime());
        return dateString;
    }

    /**
     * 得到指定日期上一周的结束时间 注意此方法仅针对中国习惯时间 即,周一是开始时间,周日是结束时间
     * 
     * @param thisTime
     * @return
     */
    public static String getLastWeekEnd(String thisTime) {
        Calendar calendar = null;
        calendar = new GregorianCalendar();
        int yy = Integer.parseInt(thisTime.split("-")[0]);
        int mm = Integer.parseInt(thisTime.split("-")[1]) - 1;
        int dd = Integer.parseInt(thisTime.split("-")[2]);
        calendar.set(yy, mm, dd);

        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - calendar.get(Calendar.DAY_OF_WEEK) + 1);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(calendar.getTime());
        return dateString;
    }

    /**
     * @param strDate String
     * @return Date
     */
    public static Date strToBirthday(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    public static String getWeekStr(String sdate) {
        String str = "";
        str = getWeek(sdate);
        if ("1".equals(str)) {
            str = "星期日";
        } else if ("2".equals(str)) {
            str = "星期一";
        } else if ("3".equals(str)) {
            str = "星期二";
        } else if ("4".equals(str)) {
            str = "星期三";
        } else if ("5".equals(str)) {
            str = "星期四";
        } else if ("6".equals(str)) {
            str = "星期五";
        } else if ("7".equals(str)) {
            str = "星期六";
        }
        return str;
    }

    /**
     * 预约时间和当前时间对比 如果返回true表示要给出提醒 yysj 格式yyyy-MM-dd HH:mm:ss
     * 
     * @return
     */
    public static boolean remainedTime(String yysj, Integer remindedMinutes) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        // long day = 0;
        // long hour = 0;
        // long min = 0;
        long interval = (remindedMinutes) * (60 * 1000);
        try {
            Date one = df.parse(yysj.trim());
            long time1 = one.getTime() + interval;
            long time2 = System.currentTimeMillis();
            // long diff;
            if (time1 < time2) {
                return true;
            } else {
                return false;
            }
            // min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            // if(min<=Globals.REMINDED_MINUTES) {
            // return true;
            // }else{
            // return false;
            // }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // throw new RuntimeException("请传入正确日期格式的字符串！");
        return false;
    }

    /**
     * 把给定的时间加上指定的时间值，可以为负。
     * 
     * @param d 日期对象
     * @param times 时间值
     * @param type 类型， Calendar.MILLISECOND,毫秒<BR>
     * Calendar.SECOND,秒<BR>
     * Calendar.MINUTE,分钟<BR>
     * Calendar.HOUR,小时<BR>
     * Calendar.DATE,日<BR>
     * @return 如果d为null，返回null
     */
    public static Date addTime(Date d, double times, int type) {
        if (d == null) {
            throw new IllegalArgumentException("参数d不能是null对象!");
        }
        long qv = 1;
        switch (type) {
            case Calendar.MILLISECOND:
                qv = 1;
                break;
            case Calendar.SECOND:
                qv = 1000;
                break;
            case Calendar.MINUTE:
                qv = 1000 * 60;
                break;
            case Calendar.HOUR:
                qv = 1000 * 60 * 60;
                break;
            case Calendar.DATE:
                qv = 1000 * 60 * 60 * 24;
                break;
            default:
                throw new RuntimeException("时间类型不正确！type＝" + type);
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        long milliseconds = Math.round(Math.abs(times) * qv);
        if (times > 0) {
            for (; milliseconds > 0; milliseconds -= 2147483647) {
                if (milliseconds > 2147483647) {
                    calendar.add(Calendar.MILLISECOND, 2147483647);
                } else {
                    calendar.add(Calendar.MILLISECOND, (int) milliseconds);
                }
            }
        } else {
            for (; milliseconds > 0; milliseconds -= 2147483647) {
                if (milliseconds > 2147483647) {
                    calendar.add(Calendar.MILLISECOND, -2147483647);
                } else {
                    calendar.add(Calendar.MILLISECOND, -(int) milliseconds);
                }
            }
        }
        return calendar.getTime();
    }

    /**
     * 把给定的时间加上指定的年份，可以为负, 返回新的被加上了年份的日期对象,不影响参数日期对象值
     * 
     * @param d
     * @param years
     * @return 日期对象
     */
    public static Date addYears(Date d, int years) {
        if (d == null) {
            throw new IllegalArgumentException("参数d不能是null对象!");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.YEAR, years);
        return calendar.getTime();
    }

    /**
     * 把给定的时间加上指定的月份，可以为负
     * 
     * @param d
     * @param months
     * @return 日期对象
     */
    public static Date addMonths(Date d, int months) {
        if (d == null) {
            throw new IllegalArgumentException("参数d不能是null对象!");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.MONTH, months);
        return calendar.getTime();
    }

    /**
     * 把给定的时间加上指定的天数，可以为负
     * 
     * @param d 日期对象
     * @param days
     * @return 日期对象
     */
    public static Date addDays(Date d, int days) {
        if (d == null) {
            throw new IllegalArgumentException("参数d不能是null对象!");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.HOUR, days * 24);
        return calendar.getTime();
    }

    /**
     * 获取一周前的时间
     * 
     * @return
     */
    public static String getBeforeWeek() {
        SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(addDays(Calendar.getInstance().getTime(), -7));
        return dateString;
    }

    /**
     * 把给定的时间加上指定的小时，可以为负
     * 
     * @param d 日期对象
     * @param hours
     * @return 日期对象
     */
    public static Date addHours(Date d, int hours) {
        if (d == null) {
            throw new IllegalArgumentException("参数d不能是null对象!");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.HOUR, hours);
        return calendar.getTime();
    }

    /**
     * 把给定的时间加上指定的分钟，可以为负
     * 
     * @param d
     * @param minutes
     * @return 日期对象
     */
    public static Date addMinutes(Date d, int minutes) {
        if (d == null) {
            throw new IllegalArgumentException("参数d不能是null对象!");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.MINUTE, minutes);
        return calendar.getTime();
    }

    /**
     * 当前时间向后推迟hours小时
     * 
     * @param minutes
     * @return
     */
    public static String addMinutes(int minutes) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, minutes);
        return dateFormatString(calendar.getTime(), DEFAULT_DATETIME_FORMAT_SEC);
    }

    /**
     * 把给定的时间加上指定的秒数，可以为负
     * 
     * @param d
     * @param seconds
     * @return 日期对象
     */
    public static Date addSeconds(Date d, int seconds) {
        if (d == null) {
            throw new IllegalArgumentException("参数d不能是null对象!");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.SECOND, seconds);
        return calendar.getTime();
    }

    /**
     * 把给定的时间加上指定的毫秒数，可以为负
     * 
     * @param d
     * @param milliseconds
     * @return 日期对象
     */
    public static Date addMilliseconds(Date d, int milliseconds) {
        if (d == null) {
            throw new IllegalArgumentException("参数d不能是null对象!");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.MILLISECOND, milliseconds);
        return calendar.getTime();
    }

    /**
     * 得到本月的最后一天
     * 
     * @return
     */
    public static String getMonthLastDay() {
        java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return format.format(calendar.getTime());
    }

    /**
     * 获取本月第一天
     * 
     * @return
     */
    public static String getMonthFirstDay() {
        java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));

        return format.format(calendar.getTime());
    }

    /**
     * 得到月最后一天
     * 
     * @param strdate
     */
    public static String lastDayOfMonth(String strdate) {
        Date date = strToDate(strdate, DEFAULT_DATE_FORMAT);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.roll(Calendar.DAY_OF_MONTH, -1);

        SimpleDateFormat formatter = new SimpleDateFormat(DateTime.DEFAULT_DATE_FORMAT);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(cal.getTime());
        return dateString;
    }

    /**
     * 得到月第一天
     * 
     * @param strdate
     */
    @SuppressWarnings("static-access")
    public static String startDayOfMonth(String strdate) {
        Date date = strToDate(strdate, DEFAULT_DATE_FORMAT);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(DEFAULT_DATE_FORMAT);
        cal.set(Calendar.DATE, 1);
        return df.format(cal.getTime());

    }

    /**
     * 得到这个月到数第二天
     * 
     * @param strdate
     */
    public static String lastSecondDayOfMonth(String strdate) {
        Date date = strToDate(strdate, YEAR_MONTH_DATETIME_FORMAT);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.roll(Calendar.DAY_OF_MONTH, -2);

        SimpleDateFormat formatter = new SimpleDateFormat(DateTime.DEFAULT_DATE_FORMAT);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(cal.getTime());
        return dateString;
    }

    /**
     * 得到上个月最后一天
     * 
     * @param strdate
     */
    public static String lastSecondDayOfLastMonth(String strdate) {
        Date date = strToDate(strdate, YEAR_MONTH_DATETIME_FORMAT);
        date = addMonths(date, -1);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.roll(Calendar.DAY_OF_MONTH, -1);

        SimpleDateFormat formatter = new SimpleDateFormat(DateTime.DEFAULT_DATE_FORMAT);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(cal.getTime());
        return dateString;
    }

    /**
     * 功能 ：返回日期型时间 2009-09-22 17:21:50
     * 
     * @param strDate
     * @return Date
     */
    public static Date strToDate(String strDate, String formatterstr) {
        SimpleDateFormat formatter = new SimpleDateFormat(formatterstr);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /**
     * 得到两个时间的相差多少月
     * 
     * @param date1
     * @param date2
     * @return
     */
    public static int calculateMonthIn(String endDate, String startDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        Calendar cal1 = new GregorianCalendar();
        Calendar cal2 = new GregorianCalendar();
        try {
            cal1.setTime(formatter.parse(startDate));
            cal2.setTime(formatter.parse(endDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        int c = (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) * 12 + cal1.get(Calendar.MONTH)
                - cal2.get(Calendar.MONTH);
        return c;
    }

    /**
     * 得到一个月相差多少天
     * 
     * @return
     */
    public static int getDaysOfMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1);
        int monthDays = calendar.getActualMaximum(5);
        return monthDays;
    }

    private static List<String> list = new ArrayList<String>();

    /**
     * 两个日期之间所有的天数 yyyy-MM-dd
     * 
     * @param start
     * @param end
     * @return
     */
    public static List<String> getDays(String start, String end) {
        if (start == null || end == null) throw new NullPointerException("开始时间，结束时间不能为空！");
        Calendar d1 = Calendar.getInstance();
        d1.setTime(strToDate(start, DEFAULT_DATE_FORMAT));
        Calendar d2 = Calendar.getInstance();
        d2.setTime(strToDate(end, DEFAULT_DATE_FORMAT));
        if (list.size() != 0) {
            list.clear();
        }

        for (; d1.before(d2); d1.add(Calendar.DAY_OF_YEAR, 1)) {
            if (null != dateFormatString(d1.getTime(), DEFAULT_DATE_FORMAT)) list.add(dateFormatString(d1.getTime(),
                                                                                                       DEFAULT_DATE_FORMAT));
        }
        list.add(end);
        return list;
    }

    /**
     * 两个日期之间所有月份
     * 
     * @param start
     * @param end
     * @return
     */
    public static List<String> getMonths(String start, String end) {
        if (start == null || end == null) throw new NullPointerException("开始时间，结束时间不能为空！");
        Calendar d1 = Calendar.getInstance();
        d1.setTime(strToDate(start, DEFAULT_TIME_MONTH_FORMAT));
        Calendar d2 = Calendar.getInstance();
        d2.setTime(strToDate(end, DEFAULT_TIME_MONTH_FORMAT));
        if (list.size() != 0) {
            list.clear();
        }
        for (; d1.before(d2); d1.add(Calendar.MONDAY, 1)) {
            if (null != dateFormatString(d1.getTime(), DEFAULT_TIME_MONTH_FORMAT)) list.add(dateFormatString(d1.getTime(),
                                                                                                             DEFAULT_TIME_MONTH_FORMAT));
        }
        list.add(end);
        return list;
    }

    /**
     * 两个日期之间所有年份
     * 
     * @param start
     * @param end
     * @return
     */
    public static List<String> getYears(String start, String end) {
        if (start == null || end == null) throw new NullPointerException("开始时间，结束时间不能为空！");
        Calendar d1 = Calendar.getInstance();
        d1.setTime(strToDate(start, DEFAULT_TIME_YEAR_FORMAT));
        Calendar d2 = Calendar.getInstance();
        d2.setTime(strToDate(end, DEFAULT_TIME_YEAR_FORMAT));
        if (list.size() != 0) {
            list.clear();
        }
        for (; d1.before(d2); d1.add(Calendar.YEAR, 1)) {
            if (null != dateFormatString(d1.getTime(), DEFAULT_TIME_YEAR_FORMAT)) list.add(dateFormatString(d1.getTime(),
                                                                                                            DEFAULT_TIME_YEAR_FORMAT));
        }
        list.add(end);
        return list;
    }

    // 得到昨天时间
    public static String getYesterday() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        return dateFormatString(calendar.getTime(), DEFAULT_DATE_FORMAT);
    }

    /**
     * date1与date2比较, 是否在date2之前
     * 
     * @param date1
     * @param date2
     * @return
     */
    public static boolean isDateBefore(String date1, String date2) {
        try {
            DateFormat df = DateFormat.getDateTimeInstance();
            return df.parse(date1).before(df.parse(date2));
        } catch (ParseException e) {
            System.out.print("[SYS] " + e.getMessage());
            return false;
        }
    }

    /**
     * 获取当前时间N小时之后的时间
     * 
     * @param after
     * @return
     */
    public static String afterHourTime(int after) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, after);
        SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT_SEC);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String dateString = formatter.format(calendar.getTime());
        return dateString;
    }

    // 得到今天开始，或者到现在的时间 flag 为 0的时候是今天开始时间 为1的时候当前时间
    public static String getTodayPoint(int flag) {
        switch (flag) {
            case 0:
                return getNowDateTime(DateTime.DEFAULT_DATE_FORMAT) + " 00:00:00";
            case 1:
                // return getNowDateTime();
                return getNowDateTime(DateTime.DEFAULT_DATE_FORMAT) + " 23:59:59";
        }

        return null;
    }

    /**
     * 得到指定月份的天数, 如果是当前月 返回当天
     * 
     * @return
     */
    public static Integer getDaysByYearMonth(Date date) {
        if (date != null) {
            if (DateTime.dateFormatString(date, DateTime.YEAR_MONTH_FORMAT).equals(DateTime.dateFormatString(null,
                                                                                                             DateTime.YEAR_MONTH_FORMAT))) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                return calendar.get(Calendar.DAY_OF_MONTH);
            } else {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);

                return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            }
        } else {
            throw new RuntimeException("getDaysByYearMonth error 参数传入错误");
        }
    }

    public static String dayBeginTime(String date) {
        return date + " 00:00:00";
    }

    public static String dayEndTime(String date) {
        return date + " 23:59:59";
    }

    /**
	 * 获取两个日期之间的日期
	 * @param start
	 * @param end
	 * @return
	 */
	public static List<String> findDates(String start, String end) {  
	 	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
	 	List<String> lDate = new ArrayList(); 
		try {
			Date dBegin= sdf.parse(start);
	        Date dEnd = sdf.parse(end);  
	        
	        Calendar calBegin = Calendar.getInstance();  
	        // 使用给定的 Date 设置此 Calendar 的时间    
	        calBegin.setTime(dBegin);  
	        Calendar calEnd = Calendar.getInstance();  
	        // 使用给定的 Date 设置此 Calendar 的时间    
	        calEnd.setTime(dEnd);  
	        // 测试此日期是否在指定日期之后    
	        while (dEnd.after(calBegin.getTime())) {  
	        	 lDate.add(sdf.format(calBegin.getTime()));
	        	 calBegin.add(Calendar.DAY_OF_MONTH, 1); 
	        }
		} catch (ParseException e) {
			e.printStackTrace();
		}  
		return lDate;
	}
	
	/**
	 * 获取某一个月的最后一天
	 * @param month
	 * @return
	 */
	public static String getLastDayOfMonth(int year,int month){
		Calendar cale = null;  
        cale = Calendar.getInstance();  
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
        String lastday;  
		cale = Calendar.getInstance(); 
		cale.set(Calendar.YEAR,year);
		cale.set(Calendar.MONTH, month);  
        cale.set(Calendar.DAY_OF_MONTH, 0);  
        lastday = format.format(cale.getTime());  
        return lastday;
	}
	/**
	 * 获取当前日期往前，往后推若干天的日期
	 * @param days
	 * @return
	 */
	public static String getDate(int days){
		Calendar cale = null;  
	    cale = Calendar.getInstance();  
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
	    String lastday;  
		cale = Calendar.getInstance();  
	    cale.add(Calendar.DATE, days);  
	    lastday = format.format(cale.getTime());  
	    return lastday;
	}
    
    public static void main(String[] args) {
    	String dz = "广东-深圳市-南山区";
    	System.out.println(dz.substring(dz.indexOf("-")+1, dz.lastIndexOf("-")));
//        System.out.println(DateTime.getStringDateTime("2013-11-21", DateTime.DEFAULT_DATE_FORMAT_CHINA));
        /*
         * System.out.println(DateTime.getEndTime(DateTime.getStringDate(), "day", -90,
         * DateTime.DEFAULT_DATETIME_FORMAT_SEC));
         */
    }

}
